package Servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.*;
import Entity.*;

public class UserListServlet extends HttpServlet {
	
	private UserListDao userlistdao = new UserListDao();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String method = request.getParameter("method");
		String path = "pages/User_List.jsp";
		boolean ac = false;
		if(method.equals("list")){
			List<UserListEntity>list = userlistdao.select();
			request.setAttribute("list", list);
		}else if(method.equals("add")){
			UserListEntity user = new UserListEntity();
			user.setCode(Integer.parseInt(request.getParameter("form_code")));
			user.setName(request.getParameter("form_name"));
			user.setSurplus(Double.parseDouble(request.getParameter("form_surplus")));
			userlistdao.add(user);
			path = "User_List_Servlet?method=list";
			ac = true;
		}else if(method.equals("update")){
			UserListEntity user = new UserListEntity();
			user.setId(Integer.parseInt(request.getParameter("form_id")));
			user.setCode(Integer.parseInt(request.getParameter("form_code")));
			user.setName(request.getParameter("form_name"));
			user.setSurplus(Double.parseDouble(request.getParameter("form_surplus")));
			userlistdao.update(user);
			path = "User_List_Servlet?method=list";
			ac = true;
		}else if(method.equals("delete")){
			userlistdao.update_delete(Integer.parseInt(request.getParameter("id")));
			path = "User_List_Servlet?method=list";
			ac = true;
		}else if(method.equals("undelete")){
			userlistdao.update_undelete(Integer.parseInt(request.getParameter("id")));
			path="User_List_Servlet?method=list";
			ac = true;
		}
		if(ac){
			response.sendRedirect(path);
		}else{
			request.getRequestDispatcher(path).forward(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
}
